package com.bawei.play.commend

import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.common.entity.CommendEntity
import com.bawei.common.entity.ReplyCommendEntity
import com.bawei.play.CustomExpandListView
import com.bawei.play.VideoPlayUiState
import com.bawei.play.VideoPlayViewIntent
import com.bawei.play.adapter.CommendExpandListAdapter
import com.bawei.play.databinding.CommendListLayoutBinding
import com.bawei.play.viewmodel.VideoPlayViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch

/**
 * 视频评论列表
 */
class CommendDialogFragment(private val itemId: String): DialogFragment(), DialogInterface.OnKeyListener {

    private lateinit var mDataBinding: CommendListLayoutBinding
    private val mViewModel: VideoPlayViewModel by activityViewModels()

    private lateinit var mRlvCommends: CustomExpandListView
    private lateinit var mExpandListCommendAdapter: CommendExpandListAdapter
    private var commendList = mutableListOf<CommendEntity>()
    private var locReplayList = mutableListOf<ReplyCommendEntity>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //取消Title
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        //获取DataBinding
        mDataBinding = CommendListLayoutBinding.inflate(inflater, container, false)
        //初始化组件
        initView()
        //初始化数据
        initData()
        //更新UI
        updateUi()
        return mDataBinding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) // 设置窗口大小
        dialog?.window?.attributes?.dimAmount = 0.2f //设置背景透明度
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) //设置背景色
        //设置取消
        dialog?.setCancelable(true)
        //设置OnKey事件
        dialog?.setOnKeyListener(this)
    }

    override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            dismiss()
            return true
        }
        return false
    }

    override fun show(manager: FragmentManager, tag: String?) {
       if(isAdded || isVisible) return
       var ft = manager.beginTransaction()
       ft.remove(this)
       ft.add(this, tag)
       ft.commitAllowingStateLoss()
    }

    override fun dismiss() {
       dismissAllowingStateLoss()
    }

    private fun initData() {
        lifecycleScope.launch {
            mViewModel.channel.send(VideoPlayViewIntent.LoadVideoCommends(0, itemId))
        }
    }

    private fun updateUi() {
       lifecycleScope.launch {
           lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED){
               collectUiState()
           }
       }
    }

    private fun initView() {
        mDataBinding.cltRoot.setOnClickListener {
            this@CommendDialogFragment.dismiss()
        }

        //取消按钮事件
        mDataBinding.ivCancel.setOnClickListener {
            this@CommendDialogFragment.dismiss()
        }
        //发送评论按钮点击事件
        mDataBinding.tvSend.setOnClickListener {
            ToastUtils.showLong("发布评论")
        }

        mRlvCommends = mDataBinding.elvComments
        mExpandListCommendAdapter = CommendExpandListAdapter(commendList)
        mRlvCommends.setAdapter(mExpandListCommendAdapter)

        //模拟评论回复数据
        mockReplyCommentData()
    }

    private fun mockReplyCommentData(){
        locReplayList.add(ReplyCommendEntity(0, 0, "我来了", "2023-12-20 14:23:21", 0, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "假的真不了", "2023-12-20 14:23:23", 1, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "言之有理", "2023-12-20 14:23:25", 2, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 3, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "啥也不是！！", "2023-12-20 14:23:26", 4, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "太傻了！！", "2023-12-20 14:23:26", 5, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 6, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "给你点赞！！", "2023-12-20 14:23:26", 7, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "努力加油！！", "2023-12-20 14:23:26", 8, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 9, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "加油！！", "2023-12-20 14:23:26", 10, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "一点儿不真实！！", "2023-12-20 14:23:26", 11, "小西", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "牛逼牛逼，太漂亮了！！", "2023-12-20 14:23:26", 12, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ))
    }

    private suspend fun collectUiState(){
        mViewModel.uiState.collect{
            when(it){
                is VideoPlayUiState.LoadVideoCommendSuccess -> {
                    if(it.list.isNotEmpty()){
                       commendList.clear()
                    }
                    //添加点回复数据
                    val locCommendSize = locReplayList.size
                    it.list.forEachIndexed { index, commendEntity ->
                        commendEntity.userlogo = "https://sf1-cdn-tos.bdxiguastatic.com/img/user-avatar/f4217ff67c16a8daf70e423cccc602fb~300x300.image"
                        commendEntity.replytotal = 3
                        //添加第一条
                        val fromIndex1 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex1, fromIndex1 + 1))
                        //添加第二条
                        val fromIndex2 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex2, fromIndex2 + 1))
                        //添加第三条
                        val fromIndex3 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex3, fromIndex3 + 1))
                    }

                    commendList.addAll(it.list)
                    mExpandListCommendAdapter.notifyDataSetChanged()

                }
                is VideoPlayUiState.LoadVideoCommendFail -> {
                    ToastUtils.showLong(it.msg)
                }
                else -> {}
            }
        }
    }

}